//
//  SubOrderViewController.m
//  LazyCat
//
//  Created by linhui on 15/12/11.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "SubOrderViewController.h"
#import "OrderCell.h"
#import "TuiHuoCell.h"
#import "MJChiBaoZiHeader.h"
#import "FeWifiManHub.h"
#import "MJChiBaoZiFooter.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "MSBluetoothManager.h"
#import "AFNetworkHandler.h"
#import "CanceOrderlViewController.h"

@interface SubOrderViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate,UIAlertViewDelegate,backDelegate,UITextFieldDelegate>
{
    NSMutableArray * _dataArray;
    UIView *_backTView;//没订单时背部提醒
    NSString * _urlIndex;//起始页
    BOOL _isLoading;
    NSString *_totalCount;//总页数
    FeWifiManHub *_loading;
    NSDictionary *dataDic;
    NSString *_teleStr;
    NSString *_order;
    NSString *_name;
    NSIndexPath *_currentIndexPath;
    NSArray *_editArr;//改变的数据源
}

@property (nonatomic, retain) CBCentralManager *centralManager;
@property (nonatomic, retain) CBPeripheral *p;
@property (nonatomic, retain) CBCharacteristic * c;

@property (nonatomic, retain) NSString *UUID;


@property (nonatomic, retain) NSMutableArray *peripheralArray;
@property (nonatomic, retain) NSMutableArray *blueNameArr;
@end
@implementation SubOrderViewController

- (void)backStr:(NSString *)str {
    if ([str isEqualToString:@"TTT"]) {
        [self loadDataaaa:nil];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if ([AppData share].isLoadd == YES) {
        NSLog(@"%d",[AppData share].isLoadd);
        [self loadDataaaa:nil];
    }
    [AppData share].isLoadd = NO;
    //_dataArray = [[NSMutableArray alloc]init];
    //[self loadData];
    NSString *swit = [ NSUserDefualManager getValueByKey:@"switch"];
    if ([swit isEqualToString:@"on"]) {
        [[MSBluetoothManager shareInstance] startScan];
        
    }

    
    
}
- (void)touchesBegan
{
    NSString *RStr = @"2764";
    NSMutableString *str = [NSMutableString new];
    [str appendFormat:@"%c", 28];
    [str appendFormat:@"%c", 33];
    [str appendFormat:@"%c", 8];
    NSLog(@"////%@",[MSBluetoothManager shareInstance].cbCharacteristcs );
    [[MSBluetoothManager shareInstance].cbPeripheral writeValue:[str dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)] forCharacteristic:[MSBluetoothManager shareInstance].cbCharacteristcs type:CBCharacteristicWriteWithResponse];
    NSString *shopName = [ShopCommonModel share].shopname; // 商家名称
    /**
     *  16.7.15 新修改字段 (2个)
     */
    NSString *realerMoney = [dataDic objectForKey:@"actualpay"];//实际(支付)金额
    NSString *youhuiMoney = [dataDic objectForKey:@"promotionamount"];//优惠的金额 （订单优惠）
    
    // 商家电话
    NSString *bossPhone = [AppData share].mobile;
    
    NSString *totalmoney = [dataDic objectForKey:@"totalmoney"]; // 总金额
    NSString *orderno = [dataDic objectForKey:@"orderno"]; // 订单号
    NSString *createtime = [dataDic objectForKey:@"createtime"]; // 下单时间
    NSString *sendDay = [dataDic objectForKey:@"sendtime"]; // 配送日期
    NSString *sendtime = [dataDic objectForKey:@"sendtimerang"]; // 配送时间
    NSString *mobile = [dataDic objectForKey:@"mobile"]; // 联系电话
    NSString *address = [dataDic objectForKey:@"address"]; // 联系地址
    NSArray *temArr = [dataDic objectForKey:@"products"]; // 商品数组
     NSString *productsnum = [dataDic objectForKey:@"productsnum"]; // 商品数量
    NSString *paytypestr = [dataDic objectForKey:@"paytype"]; // 支付方式
    NSString *onlinePay = [dataDic objectForKey:@"orderpayamount"];//订单金额
    NSString *yuePay = [dataDic objectForKey:@"yue"];
    NSString *jifenPay = [dataDic objectForKey:@"fenxiangjf"];
    NSString *yhqPay = [dataDic objectForKey:@"newcouponpay"];
    NSString *lcatcoupanpaytl = [dataDic objectForKey:@"lcatcoupanpaytl"];//懒猫券抵扣总金额
    
    NSString *product = @"";
    for (int i = 0; i < temArr.count; i++) {
        NSString *pName = [temArr[i] objectForKey:@"productname"]; // 商品名字
        NSString *price = [temArr[i] objectForKey:@"price"]; // 商品价格
        NSString *numbuy = [temArr[i] objectForKey:@"numbuy"]; // 商品数量
        NSString *lcatcouponpay = [temArr[i] objectForKey:@"lcatcouponpay"]; //懒猫券抵扣（单个商品）金额
        if (lcatcouponpay.length == 0 || [lcatcouponpay floatValue] <= 0) {
            lcatcouponpay = @"";
            product = [NSString stringWithFormat:@"%@\n%@\n                x%@       %@\n",product,pName,numbuy,price];
            
        }else{
            product = [NSString stringWithFormat:@"%@\n%@\n                x%@       %@\n             懒猫券抵扣 ：%@\n",product,pName,numbuy,price,lcatcouponpay];
            
        }
    }
    
    NSString *lcatCoupanStr;
    if (lcatcoupanpaytl.length == 0 || [lcatcoupanpaytl floatValue] <= 0)
    {
        lcatCoupanStr = @"";
    }else {
        lcatCoupanStr = [NSString stringWithFormat:@"\n懒猫券抵扣:%@",lcatcoupanpaytl];
    }
    
    NSString *realMoneyStr;
    if ([realerMoney floatValue] == 0) {
        realMoneyStr = @"";
    }else {
        realMoneyStr = [NSString stringWithFormat:@"\n实际金额:%@",realerMoney];
    }
    
    NSString *youhuiMoneyStr;
    if ([youhuiMoney floatValue] == 0) {
        youhuiMoneyStr = @"";
    }else {
        youhuiMoneyStr = [NSString stringWithFormat:@"\n已优惠:%@",youhuiMoney];
    }
    
    NSString *onlinePayStr;
    if ([onlinePay floatValue] == 0)
    { onlinePayStr = @"";}
    else {
        onlinePayStr = [NSString stringWithFormat:@"\n订单支付:%@",onlinePay];
    }
    
    NSString *yuePayStr;
    if ([yuePay floatValue] == 0) { yuePayStr = @"";}
    else {
        yuePayStr = [NSString stringWithFormat:@"\n余额支付:%@",yuePay];
    }
    
    NSString *jifenPayStr;
    if ([jifenPay floatValue] == 0) {
        jifenPayStr = @"";
    }else {
        jifenPayStr = [NSString stringWithFormat:@"\n积分抵扣:%@",jifenPay];
    }
    
    NSString *yhqPayStr;
    if ([yhqPay floatValue] == 0) {
        yhqPayStr = @"";
    }else {
        yhqPayStr = [NSString stringWithFormat:@"\n优惠券抵扣:%@",yhqPay];
    }
    
    NSString *totalMoneyStr;
    if ([totalmoney floatValue] == 0) {
        totalMoneyStr = @"";
    }else {
        totalMoneyStr = [NSString stringWithFormat:@"\n消费总金额:%@",totalmoney];
    }
    
   RStr = [NSString stringWithFormat:@"\n商家名称:%@\n社长电话:%@\n订单号:%@\n下单时间:%@\n配送日期:%@\n配送时间:%@\n联系电话:%@\n联系地址:%@\n------------------------------\n商品名称       数量      金额\n------------------------------\n%@\n------------------------------%@%@\n商品总数量:%@\n支付方式:%@%@%@%@%@%@%@\n------------------------------\n 懒猫社长\n\n\n",shopName,bossPhone,orderno,createtime,sendDay,sendtime,mobile,address,product,totalMoneyStr,youhuiMoneyStr,productsnum,paytypestr,yuePayStr,jifenPayStr,yhqPayStr,onlinePayStr,lcatCoupanStr,realMoneyStr];
    //    RStr = @"杜博 你好呀!!!\n我很好\n啦啦啦\n啦啦啦\n啦啦\n啦啦啦\n啦啦啦\n啦啦\n";
//    if (lcatcoupanpaytl.length == 0 || [lcatcoupanpaytl floatValue] <= 0) {
//        RStr = [NSString stringWithFormat:@"\n商家名称:%@\n社长电话:%@\n订单号:%@\n下单时间:%@\n配送日期:%@\n配送时间:%@\n联系电话:%@\n联系地址:%@\n------------------------------\n商品名称       数量      金额\n------------------------------\n%@\n------------------------------\n商品总数量:%@\n支付方式:%@\n在线支付:%@\n余额支付:%@\n积分抵扣:%@\n优惠券抵扣:%@\n消费总金额:%@\n------------------------------\n 懒猫社长\n\n\n",shopName,bossPhone,orderno,createtime,sendDay,sendtime,mobile,address,product,productsnum,paytypestr,onlinePay,yuePay,jifenPay,yhqPay,totalmoney];
//    }else{
//        RStr = [NSString stringWithFormat:@"\n商家名称:%@\n社长电话:%@\n订单号:%@\n下单时间:%@\n配送日期:%@\n配送时间:%@\n联系电话:%@\n联系地址:%@\n------------------------------\n商品名称       数量      金额\n------------------------------\n%@\n------------------------------\n商品总数量:%@\n支付方式:%@\n在线支付:%@\n余额支付:%@\n积分抵扣:%@\n懒猫券抵扣:%@\n优惠券抵扣:%@\n消费总金额:%@\n------------------------------\n 懒猫社长\n\n\n",shopName,bossPhone,orderno,createtime,sendDay,sendtime,mobile,address,product,productsnum,paytypestr,onlinePay,yuePay,jifenPay,lcatcoupanpaytl,yhqPay,totalmoney];
//    }

   
    NSData *nsdata =  [RStr dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
    [[MSBluetoothManager shareInstance] writeData:nsdata];
 
}




//====================================================================================
//====================================================================================
//====================================================================================


- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self loadData];
    [AppData share].isLoadd = NO;
//    [self addRefresh];
    self.tableView.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(addRefresh)];
    //[self loadMore];
    
}
- (void)createUI {
    self.view.backgroundColor = BackColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    _backTView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    _backTView.backgroundColor = BackColor;
    _backTView.hidden = YES;
    [self.view addSubview:_backTView];
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 80)/2, 100, 80, 90)];
    backImage.image = [UIImage imageNamed:@"noOrder"];
    [_backTView addSubview:backImage];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake((ScreenWidth - 200)/2, backImage.frame.origin.y + 90, 200, 50)];
    label.textColor = SetColor(153, 153, 153, 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"您暂时还没有相关订单";
    [_backTView addSubview:label];
    
    _urlIndex = @"1";
    _loading = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
    _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y - 104, _loading.frame.size.width, _loading.frame.size.height);
    [self.view addSubview:_loading];
    [_loading show];
    _dataArray = [[NSMutableArray alloc]init];
    _isLoading = NO;
    MJRefreshAutoFooter *foot = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    self.tableView.footer = foot;
    _dataArray = [[NSMutableArray alloc]init];
}
- (void)loadData {
    NSString *kUrl;
    if (self.keyWord == nil) {
        self.keyWord = @"";
    }
    NSString *name = [NSUserDefualManager getValueByKey:UserName];
    if (_tuiHuoManager) {
        if(self.currentPage == 0){
            kUrl = [NSString stringWithFormat:tuiHuoMUrl,@"15",_urlIndex,name,@"0"];
        }else if(self.currentPage == 1){
            kUrl = [NSString stringWithFormat:tuiHuoMUrl,@"15",_urlIndex,name,@"1"];
        }else if(self.currentPage == 2){
            kUrl = [NSString stringWithFormat:tuiHuoMUrl,@"15",_urlIndex,name,@"3"];
        }else if(self.currentPage == 3){
            kUrl = [NSString stringWithFormat:tuiHuoMUrl,@"15",_urlIndex,name,@"6"];
        }else if(self.currentPage == 4){
            kUrl = [NSString stringWithFormat:tuiHuoMUrl,@"15",_urlIndex,name,@""];
        }
    }else {
        if(self.currentPage == 0){
            kUrl = [NSString stringWithFormat:OrderUrl,@"15",_urlIndex,name,@"1",self.keyWord];
        }else if(self.currentPage == 1){
            kUrl = [NSString stringWithFormat:OrderUrl,@"15",_urlIndex,name,@"2",self.keyWord];
        }else if(self.currentPage == 2){
            kUrl = [NSString stringWithFormat:OrderUrl,@"15",_urlIndex,name,@"3",self.keyWord];
        }else if(self.currentPage == 3){
            kUrl = [NSString stringWithFormat:OrderUrl,@"15",_urlIndex,name,@"",self.keyWord];
        }
    }
    if ([_urlIndex isEqualToString:@"1"]) {
        [_dataArray removeAllObjects];
    }
    [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
//    [AFNetworkHandler GETWithAFNByURL:kUrl completion:^(id result) {
        NSDictionary *dic = networkRequest.responseData;
        NSLog(@"%@",networkRequest.responseData);
        
        NSLog(@"error:%@",error);
        _totalCount = [dic objectForKey:@"totalpage"];
        NSArray *arr = [dic objectForKey:@"orders"];
        [_dataArray addObjectsFromArray:arr];
        _editArr = arr;
        _isLoading = NO;
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        [_loading dismiss];
        
        [_loading removeFromSuperview];
        if ([_totalCount isEqualToString:@"0"] || _totalCount == nil) {
            _backTView.hidden = NO;
        }else {
            _backTView.hidden = YES;
        }
        NSLog(@"dataArr:%@",_dataArray);
        [self.tableView reloadData];
    }];
    if (kNetworkNotReachability) {
        [_loading dismiss];
        [_loading removeFromSuperview];
    }
}
//*----------/////
- (void)loadDataaaa:(NSIndexPath *)indexPath {
    if (self.keyWord == nil) {
        self.keyWord = @"";
    }
    NSString *kUrl;
    NSString *numCount;//数据量
    NSInteger count = ([_urlIndex integerValue] - 1) * 15 +_editArr.count;//数据量
    numCount = [NSString stringWithFormat:@"%ld",count];
    NSString *name = [NSUserDefualManager getValueByKey:UserName];
    if (_tuiHuoManager) {
        if(self.currentPage == 0){
            kUrl = [NSString stringWithFormat:tuiHuoMUrl,numCount,@"1",name,@"0"];
        }else if(self.currentPage == 1){
            kUrl = [NSString stringWithFormat:tuiHuoMUrl,numCount,@"1",name,@"1"];
        }else if(self.currentPage == 2){
            kUrl = [NSString stringWithFormat:tuiHuoMUrl,numCount,@"1",name,@"3"];
        }else if(self.currentPage == 3){
            kUrl = [NSString stringWithFormat:tuiHuoMUrl,numCount,@"1",name,@"6"];
        }else if(self.currentPage == 4){
            kUrl = [NSString stringWithFormat:tuiHuoMUrl,numCount,@"1",name,@""];
        }
    }else {
        if(self.currentPage == 0){
            kUrl = [NSString stringWithFormat:OrderUrl,numCount,@"1",name,@"1",self.keyWord];
        }else if(self.currentPage == 1){
            kUrl = [NSString stringWithFormat:OrderUrl,numCount,@"1",name,@"2",self.keyWord];
        }else if(self.currentPage == 2){
            kUrl = [NSString stringWithFormat:OrderUrl,numCount,@"1",name,@"3",self.keyWord];
        }else if(self.currentPage == 3){
            kUrl = [NSString stringWithFormat:OrderUrl,numCount,@"1",name,@"",self.keyWord];
        }
    [_dataArray removeAllObjects];
        NSLog(@"%@",_dataArray);
    [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        _totalCount = [dic objectForKey:@"totalpage"];
        NSArray *arr = [dic objectForKey:@"orders"];
        [_dataArray addObjectsFromArray:arr];
        if ([_totalCount isEqualToString:@"0"] || _totalCount == nil) {
            _backTView.hidden = NO;
        }else {
            _backTView.hidden = YES;
        }
        [self.tableView reloadData];
    }];
}
}
//下拉刷新
- (void)addRefresh {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
//    MJChiBaoZiHeader *header = [MJChiBaoZiHeader headerWithRefreshingBlock:^{
        _urlIndex = @"1";
//        [header beginRefreshing];
        [self loadData];
    
    [self.tableView.header endRefreshing];
//    }];
//    self.tableView.header = header;
//    header.lastUpdatedTimeLabel.hidden = YES;
}
//上拉加载
- (void)loadMore {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    //MJRefreshAutoFooter *foot = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        if ([_urlIndex integerValue] >= [_totalCount integerValue]) {
            [[MessShowView share]showWithMess:@"没有更多数据"];
            return ;
        }
            _urlIndex = [NSString stringWithFormat:@"%ld",[_urlIndex integerValue]+1];
            //[foot beginRefreshing];
            [self loadData];
    
    //}];
    //self.tableView.footer = foot;
}
//列表4个按钮的点击事件
- (void)btnClick:(UIButton *)sender event:(id)event {
    //取indexpath
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath= [self.tableView indexPathForRowAtPoint:currentTouchPosition];
    _currentIndexPath = indexPath;
    NSLog(@"我在%ld行，编号%ld",indexPath.row,sender.tag);
    if (indexPath!= nil)
    {
        if (indexPath.row < [_dataArray count]){
            _order = [_dataArray[indexPath.row] objectForKey:@"orderno"];
        }
        _name = [AppData share].username;
        if (sender.tag == 332) {//取消订单
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"确认取消" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
            alert.tag = 501;
            [alert show];
        }else if (sender.tag == 333) {//订单发货
            UIAlertView *fahuoAlert = [[UIAlertView alloc]initWithTitle:nil message:@"确认发货" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
            fahuoAlert.tag = 502;
            [fahuoAlert show];
        }else if (sender.tag == 334){ // 打印小票
            dataDic = [NSDictionary dictionary];
            dataDic =  _dataArray[indexPath.row];
            [self touchesBegan];
        }else if (sender.tag == 335){//联系买家
            if (indexPath.row < [_dataArray count]) {
            NSString *mobile = [_dataArray[indexPath.row] objectForKey:@"mobile"];
            NSString *user = [_dataArray[indexPath.row]objectForKey:@"linkman"];
            
            if (user == nil) {
                user = @"";
            }
            NSMutableString * str1=[[NSMutableString alloc] initWithFormat:@"tel://%@",mobile];
            _teleStr = str1;
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:@"买家姓名:%@\n联系电话：%@\n是否通话？",user,mobile] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 503;
            [alert show];
            }
        }
    }
}
//列表四个按钮
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 501) {//取消订单
        if (buttonIndex == 1) {
//            NSString *url = [NSString stringWithFormat:quxiaoOrder,_order,[AppData share].username];
            CanceOrderlViewController *cancel = [[CanceOrderlViewController alloc]init];
            cancel.orderNumber = _order;
            cancel.delegate = self;
            cancel.orderType = @"0";
            if (_myBlock) {
                _myBlock(cancel);
            }
        }
    }else if (alertView.tag == 503) {//联系买家
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_teleStr]];
        }else {
            return;
        }
    }else if (alertView.tag == 502){//订单发货
        if (buttonIndex == 1) {
            NSString *url = [NSString stringWithFormat:fahuoOrder,_order,_name];
            [NTNetUtil sendRequestWithUrl:url requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
                NSDictionary *dic = networkRequest.responseData;
                NSString *result = [dic objectForKey:@"m"];
                
                if ([result isEqualToString:@"success"]) {
                    [[MessShowView share]showWithMess:@"订单发货成功" login:YES];
                    [_dataArray removeObjectAtIndex:_currentIndexPath.row];
                    [self.tableView reloadData];
                }else  {
                    [[MessShowView share]showWithMess:@"订单发货失败" login:NO];
                }
            }];
        }
    }
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_tuiHuoManager) {//退货管理
        TuiHuoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tuihuocell"];
        if (cell == nil) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"TuiHuoCell" owner:nil options:nil][0];
        }
        [cell.tuiHuoBtn addTarget:self action:@selector(tuiHuoBtnClicl:event:) forControlEvents:UIControlEventTouchUpInside];
        if (indexPath.row < [_dataArray count]) {////////防止数组越界
            cell.orderNum.text = [NSString stringWithFormat:@"订单号：%@",[_dataArray[indexPath.row]objectForKey:@"originalorderno"]];
            cell.orderNum.textColor = SetColor(51, 51, 51, 1);
            cell.stateLabel.text = [_dataArray[indexPath.row]objectForKey:@"orderstatusstr"];
            cell.shenQingLabel.text = [NSString stringWithFormat:@"申请时间：%@",[_dataArray[indexPath.row]objectForKey:@"createtime"]];
            cell.shenQingLabel.textColor = SetColor(102, 102, 102, 1);
            cell.userLabel.text = [NSString stringWithFormat:@"退款用户：%@",[_dataArray[indexPath.row]objectForKey:@"orderuser"]];
            cell.userLabel.textColor = SetColor(102, 102, 102, 1);
            cell.backgroundColor = BackColor;
            cell.stateLabel.textColor = MainColorT;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
    }else {//订单管理
        OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"orderCell"];
        if (cell == nil) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"OrderCell" owner:nil options:nil][0];
        }
        [cell.deFa addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
        [cell.daYin addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
        [cell.lianXi addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
        [cell.quXiao addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
        [cell.backQuxiaoBtn addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
        cell.backgroundColor = BackColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //NSDictionary *products = [_dataArray[indexPath.row] objectForKey:@"products"][0];
        //产品数组
        if (indexPath.row < [_dataArray count]) {////////防止数组越界
            NSArray *productsArr = [_dataArray[indexPath.row] objectForKey:@"products"];
            UIImageView *imageView;
            //清空所有显示图片（防止重用时混乱）
            for (int i = 0; i < 6; i ++) {
            imageView = (UIImageView *)[cell viewWithTag:100 + i];
                imageView.image = nil;
            }
            //铺图片
            for (int i = 0; i < productsArr.count; i ++) {
                if (i <= 5) {
                    imageView = (UIImageView *)[cell viewWithTag:100+i];
                    [imageView sd_setImageWithURL:[NSURL URLWithString:[productsArr[i] objectForKey:@"img"]]];
                }
            }/////
            //"isdisplaycancelorderbutton": "1",//是否显示取消订单按钮
            //"isdisplayfahuobutton": "0",//是否显示发货按钮
            NSString *isCancelShow = [_dataArray[indexPath.row] objectForKey:@"isdisplaycancelorderbutton"];
            NSString *isFahuoShow = [_dataArray[indexPath.row] objectForKey:@"isdisplayfahuobutton"];
            if ([isCancelShow isEqualToString:@"0"]) {
                cell.quXiao.hidden = YES;
            }
            if ([isFahuoShow isEqualToString:@"0"]) {
                cell.deFa.hidden = YES;
                if ([isCancelShow isEqualToString:@"1"]) {
                    cell.quXiao.hidden = YES;
                    cell.backQuxiaoBtn.hidden = NO;
                }
            }
            cell.deseLabel.text = [productsArr[0] objectForKey:@"productname"];
            cell.moneyLabel.text = [NSString stringWithFormat:@"¥%@",[productsArr[0] objectForKey:@"price"]];
            cell.countLabel.text = [NSString stringWithFormat:@"x%@",[productsArr[0] objectForKey:@"numbuy"]];
            if (productsArr.count>1) {
                cell.deseLabel.hidden = YES;
                cell.moneyLabel.hidden = YES;
                cell.countLabel.hidden = YES;
            }else {
                cell.deseLabel.hidden = NO;
                cell.moneyLabel.hidden = NO;
                cell.countLabel.hidden = NO;
            }
            cell.orderNumLabel.text = [NSString stringWithFormat:@"订单号:%@",[_dataArray[indexPath.row] objectForKey:@"orderno"]];
            cell.statuesLabel.text = [_dataArray[indexPath.row] objectForKey:@"orderstatustext"];
            [cell.InBtn addTarget:self action:@selector(inBtnClicl:event:) forControlEvents:UIControlEventTouchUpInside];
            if ([[_dataArray[indexPath.row]objectForKey:@"iscod"] isEqualToString:@"1"]) {
                cell.huodaofukuanLabel.text = @"货到付款";
            }
            cell.statuesLabel.textColor = MainColorT;
            cell.sendTimeLabel.text = [NSString stringWithFormat:@"下单时间:%@",[_dataArray[indexPath.row] objectForKey:@"createtime"]]
            ;
            cell.sendTimeLabel.textColor = SetColor(153, 153, 153, 1);
            
            // 快递费
            NSString *serviceMoney = [_dataArray[indexPath.row] objectForKey:@"addservicefee"];
            NSString *productNum = [_dataArray[indexPath.row] objectForKey:@"productsnum"];
            NSString *realyMoney = [_dataArray[indexPath.row] objectForKey:@"actualpay"];
            
            NSString *sumContentStr = [NSString stringWithFormat:@"共%@件商品 合计¥%@ (含运费¥%@)",productNum,realyMoney,serviceMoney];
            if ([serviceMoney floatValue] == 0)
            {
                sumContentStr = [NSString stringWithFormat:@"共%@件商品 合计¥%@",productNum,realyMoney];
            }
            
            cell.sumContentLabel.text = sumContentStr;
            //}/////////
            if ([[_dataArray[indexPath.row] objectForKey:@"sendmethod"]isEqualToString:@""]) {
                cell.xiaDanTimeLabel.text = @"配送方式:及时送达";
            }else {
                cell.xiaDanTimeLabel.text = [NSString stringWithFormat:@"配送方式：%@",[_dataArray[indexPath.row] objectForKey:@"sendmethod"]];
            }
            cell.countLabel.textColor = SetColor(153, 153, 153, 1);
//            if (_currentPage == 1) {
//                cell.deFa.hidden = YES;
//            }else if (_currentPage == 2 || _currentPage == 3) {
//                cell.deFa.hidden = YES;
//                //cell.daYin.hidden = YES;
//            }
            if (_dataArray.count == 0) {
                _backTView.hidden = NO;
            }
        }
        return cell;
    }
}
//订单cell点击
- (void)inBtnClicl:(UIButton *)sender event:(id)event{
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath= [self.tableView indexPathForRowAtPoint:currentTouchPosition];
//    if (kNetworkNotReachability) { // 没网
//        [[MessShowView share] showWithMess:@"当前网络不给力"];
//        return;
//    }else {
    if (indexPath!= nil)  {
        DetailOrderVC *detail = [[DetailOrderVC alloc]init];
        //"isdisplaycancelorderbutton": "1",//是否显示取消订单按钮
        //"isdisplayfahuobutton": "0",//是否显示发货按钮
        if (indexPath.row < [_dataArray count]) {
            NSString *isCancelShow = [_dataArray[indexPath.row] objectForKey:@"isdisplaycancelorderbutton"];
            NSString *isFahuoShow = [_dataArray[indexPath.row] objectForKey:@"isdisplayfahuobutton"];
            NSString *isYanShi = [_dataArray[indexPath.row]objectForKey:@"isdisplaydelaysendgoodsbutton"];
            //传值
            detail.orderNum = [_dataArray[indexPath.row] objectForKey:@"orderno"];
            detail.teleNum = [_dataArray[indexPath.row]objectForKey:@"mobile"];
            detail.quxiao = isCancelShow;
            detail.fahuo = isFahuoShow;
            detail.yanshi = isYanShi;
            detail.dataArrray = _dataArray[indexPath.row];
        }
        if (_myBlock) {
            _myBlock(detail);
        }
    //}
    }
}
//退货管理cell点击
- (void)tuiHuoBtnClicl:(UIButton *)sender event:(id)event{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
//    if (kNetworkNotReachability) { // 没网
//        [[MessShowView share] showWithMess:@"当前网络不给力"];
//        return;
//    }else{
    if (indexPath != nil) {
        DetailOrderVC *detail = [[DetailOrderVC alloc]init];
        if (indexPath.row < [_dataArray count]) {//数组越界
            detail.orderNum = [_dataArray[indexPath.row] objectForKey:@"refundorderno"];
            detail.tuiHuoManager = _tuiHuoManager;
            detail.clzBtn = [_dataArray[indexPath.row] objectForKey:@"isDisplayprocessingbutton"];
            detail.juJue = [_dataArray[indexPath.row] objectForKey:@"isDisplayrefusebutton"];
            detail.tongYi = [_dataArray[indexPath.row] objectForKey:@"isDisplayagreebutton"];
            detail.wanCheng = [_dataArray[indexPath.row]objectForKey:@"isDisplayrefundwanchengbutton"];
        detail.dataArrray = _dataArray[indexPath.row];
        }
        if (_myBlock) {
            _myBlock(detail);
        }
    }
    //}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_tuiHuoManager) {
        return 115;
    }else {
        return 220;
    }
}
@end
